#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <functional>

#include "Log.hpp"
#include "Common.hpp"
#include "IntAddr.hpp"
#include "ThreadPool.hpp"

#define BACKLOG 8

using namespace LogModule;
using namespace ThreadPoolModule;

static const uint16_t gport = 8082;
//处理的任务类型, 返回值为string , 参数为string
using handler_t = std::function<std::string(std::string)>;

class TcpServer
{
    using task_t = std::function<void()>;
    struct ThreadData
    {
        int sockfd;
        TcpServer *self;
    };
public:
    TcpServer( int port = gport)
        : _port(port)
        , _isrunning(false)
        {}
    //初始化服务器
    void InitServer()
    {
        //1. 创建tcp socket
        //tcp所创建的socket只用来起到监听作用
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if(_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error";
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "sicket create success, sockfd is: " << _listensockfd;

        //设置选项
        int opt = 1;
        setsockopt(_listensockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        //设置网络信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(gport);
        local.sin_addr.s_addr = INADDR_ANY;

        //2.绑定
        int n = ::bind(_listensockfd, CONV(&local), sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success : " << _listensockfd;

        //3.cs, tcp是面向连接的, 就要求tcp随时随地等待被连接
        //tcp需要把socket设置为监听状态
        n = ::listen(_listensockfd, BACKLOG);
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "lesson error";
            Die(LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success, lesonsockfd is: " << _listensockfd;


    }

    void HandlerRequst(int sockfd)
    {
        LOG(LogLevel::INFO) << "HandlerRequest, sockfd is: " << sockfd;
        char inbuffer[4096];
        //长任务
        while(true)
        {
            //约定: 用户发来的是一个完整的命令string
            //read读取的是不完整的
            ssize_t n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if(n > 0)
            {
                inbuffer[n] = 0;
                LOG(LogLevel::INFO) << inbuffer;
            
                std::string echo_str = "server echo# ";
                echo_str += inbuffer;
                // std::string cmd_result = _handler(inbuffer);

                ::send(sockfd, echo_str.c_str(), echo_str.size(), 0);
            }
            else if(n == 0)
            {
                //read如果返回值为0, 表示client退出
                LOG(LogLevel::INFO) << "client quit: " << sockfd;
                break;   
            }
            else
            {
                break; //读取失败
            }
        }
        ::close(sockfd); //防止fd泄露
    }

    void Start()
    {
        _isrunning = true;
        while(_isrunning)
        {
            //不能直接读取数据
            //1.获取链接 accept
            struct sockaddr_in peer;
            socklen_t perrlen = sizeof(peer); 
            LOG(LogLevel::DEBUG) << "accept ing...";
            int sockfd = ::accept(_listensockfd, CONV(&peer), &perrlen);
            //此时的sockfd才是我们通信的
            if(sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error: " << strerror(errno);
                continue; 
            }
            //获取连接成功了
            LOG(LogLevel::INFO) << "accept success, sockfd is : " << sockfd;
            InetAddr addr(peer);
            LOG(LogLevel::INFO) << "client info: " << addr.Addr();

            //version-0
            HandlerRequst(sockfd);

        }
    }
    void Stop()
    {
        _isrunning = false;
    }
    ~TcpServer()
    {
    }
private:
    int _listensockfd; //监听
    uint16_t _port;
    bool _isrunning;

    //处理上层任务的入口
    //handler_t _handler;
};